<template>
  <div class="imgUpload">
    <el-upload class="upload"
        :action="uploadApi" :file-list="fileLists"
        :list-type="listType"
        :accept="fileType"
        :show-file-list="showFiles"
        :on-remove="fileRemove"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :headers="headers" :limit="limit"
        :data="sendData"
        v-if="!disabled">
        <i slot="default" class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import AuthButton from '@/components/auth/authButton'
  import { getHeaders } from '@/utils/devUtils'
  // import { getToken } from '@/utils/auth'
  export default {
    components: {AuthButton},
    props: {
      // 所属菜单Code-->全局唯一
      menuCode: {
        type: String,
        default: null
      },
      // 按钮权限标识，外部使用者传入
      perms: {
        type: String,
        default: null
      },
      // 文件ID
      fileID: {
        type: [String, Number],
        default: function () {
          return null
        }
      },
      // 是否显示上传文件
      showFiles: {
        type: Boolean,
        default: false
      },
      // 文件名
      fileName: {
        type: String,
        default: function () {
          return null
        }
      },
      // 所属类型CODE
      belongCode: {
        type: String,
        // required: true,
        default: function () {
          return 'GYS'
        }
      },
      // 是否拖拽
      drag: {
        type: Boolean,
        default: function () {
          return false
        }
      },
      // 所属业务ID
      belongID: {
        type: String,
        // required: true,
        default: function () {
          return null
        }
      },
      // 限制文件类型
      fileType: {
        type: String,
        default: function () {
          return '.png,.jpg'
        }
      },
      // 限制文件大小(M)
      fileSize: {
        type: Number,
        default: function () {
          return 50
        }
      },
      // 文件管理服务上传地址
      uploadApi: {
        type: String,
        // required: true,
        default: function () {
          return '/restapi/file/fastdfs/upload/file'
        }
      },
      showImageApi: {
        type: String,
        default: function () {
          return '/restapi/file/fastdfs/download/imageById?id='
        }
      },
      // 行数据
      rowData: {
        type: Object,
        default: function () {
          return null
        }
      },
      // 行号
      rowIndex: {
        type: Number,
        default: function () {
          return null
        }
      },
      // 按钮大小
      btnSize: {
        type: String,
        default: function () {
          return 'small'
        }
      },
      // index
      index: {
        type: Number,
        default: function () {
          return null
        }
      },
      // 上传按钮显示内容
      uploadName: {
        type: String,
        default: function () {
          return '上传'
        }
      },
      // 重新上传按钮显示内容
      reUploadName: {
        type: String,
        default: function () {
          return '重新上传'
        }
      },
      // 上传之前方法
      uploadbefore: {
        type: Function,
        default: function () {
          return true
        }
      },
      // 数据回显类型 text/picture/picture-card
      listType: {
        type: String,
        default: 'picture-card'
      },
      // 限制上传文件个数
      limit: {
        type: Number,
        default: null
      },
      disabled: {
        type: Boolean,
        default: false
      },
      value: {
        type: [String, Array],
        default: ''
      },
      singleUpload: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        fullscreenLoading: false,
        newFileName: this.fileName,
        headers: getHeaders(),
        imageUrl: '',
        dialogImageUrl: '',
        dialogVisible: false,
        disableds: false,
        attachmentId: '',
        isInit: true, // 是否是第一次进来
        // 数据回显
        fileLists: []
        // fileLists: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      }
    },
    created () {
      this.attachmentId = this.value
    },
    computed: {
      sendData: function () {
        return {
          belongCode: this.belongCode,
          belongID: this.belongID
        }
      },
      currentFileId: {
        get: function () {
          return this.fileID
        },
        set: function (val) {
          return this.$emit('update:fileID', val)
        }
      },
      label () {
        // 数据库字段不能为空，默认为零
        return this.UtilJs.isEmpty(this.currentFileId) || this.currentFileId === '0' ? this.uploadName : this.reUploadName
      }
    },
    watch: {
      'fileID' (val) {
        if (val) {
          this.showImg(val)
        }
      },
      value: {
        immediate: true,
        handler: function (val, old) {
          if (this.isInit) {
            this.showImg(val)
          }
          this.attachmentId = this.value
        }
      },
      attachmentId (val, old) {
        this.$emit('input', val)
      }
    },
    methods: {
      beforeUpload (file) {
        this.isInit = false
        if (!this.uploadbefore(file)) {
          return false
        }
        if (!this.UtilJs.isNull(this.fileSize) && file.size / 1024 > this.fileSize * 1024) {
          this.warning(`已超出上传文件最大限制${this.fileSize}M`)
          return false
        }
        var fileType = '.' + file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
        var banFileTypes = ['.exe', '.bat', '.cmd', '.sh', '.py']
        var banFileTypeFlag = 0
        banFileTypes.forEach(item => {
          if (item === fileType) {
            banFileTypeFlag = 1
          }
        })
        if (banFileTypeFlag === 1) {
          this.warning('不允许上传' + fileType.substring(fileType.lastIndexOf('.') + 1) + '文件')
          return false
        }
        if (!this.UtilJs.isNull(this.fileType)) {
          var fileTypeFlag = 0
          var fileTypeList = this.fileType.toLowerCase().split(',')
          fileTypeList.forEach(it => {
            if (fileType === it) {
              fileTypeFlag = 1
            }
          })
          if (fileTypeFlag === 0) {
            this.warning('只能上传' + this.fileType.toLowerCase().replace(/\./g, '') + '文件')
            return false
          }
        }
        let returnData = {}
        returnData.rowData = this.rowData
        returnData.rowIndex = this.rowIndex
        returnData.index = this.index
        this.$emit('beforeUpload', returnData)
        this.fullscreenLoading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return true
      },
      fileRemove (file, fileList) {
        this.isInit = false
        if (this.attachmentId.indexOf(',') > -1) {
          let arr = this.attachmentId.split(',')
          if (arr.length !== 0) {
            arr.map((_, index) => {
              if (file.response && file.response.data.fileId === _) {
                arr.splice(index, 1)
              } else if (file.url.substring(file.url.indexOf('id=') + 3, file.url.length) === _) {
                arr.splice(index, 1)
              }
            })
            if (arr.length !== 0) {
              this.attachmentId = arr.join(',')
            } else {
              this.attachmentId = ''
            }
          }
        } else {
          // 当只有一个数据时
          this.attachmentId = ''
        }
        this.$emit('fileRemove', this.attachmentId, fileList)
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
        console.log('fileLists', this.fileLists)
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleDownload (file) {
        console.log(file)
      },
      uploadSuccess (response, file, fileList) {
        if (response.code !== 0) {
          this.fullscreenLoading.close()
          this.error(response.message)
          return
        }
        let returnData = {}
        returnData.rowData = this.rowData
        returnData.rowIndex = this.rowIndex
        returnData.index = this.index
        returnData.fileId = response.data.fileId
        returnData.fileName = response.data.fileName
        returnData.attachmentId = response.data.fileId
        // 是否只能传一张
        if (this.singleUpload) {
          this.attachmentId = response.data.fileId
        } else {
          if (this.attachmentId) {
            this.attachmentId = this.attachmentId + ',' + response.data.fileId
          } else {
            this.attachmentId = response.data.fileId
          }
        }
        returnData.nodeName = response.data.fileName
        this.$emit('uploadSuccess', returnData, this.rowIndex, this.rowData, fileList)
        this.fullscreenLoading.close()
      },
      showImg (val) {
        if (!val) return
        let arr = val.split(',')
        if (arr.length !== 0) {
          arr.map(_ => {
            if (_) {
              if (this.singleUpload && this.fileLists.length !== 0) {
                this.fileLists = []
              }
              this.$nextTick(() => {
                this.fileLists.push({
                  url: this.showImageApi + _
                })
              })
            }
          })
        }
        this.isInit = false
      }
    }
  }
</script>

<style scoped>
  .upload{
    display:inline-block;
    margin: 0 9px 0 1px;
  }
  .imgUpload .fileImg {
    width: 80px;
    height: 80px;
    vertical-align: top;
  }
  .imgUpload .fileImg:hover {
    cursor: pointer;
  }
</style>
<style lang="scss">
  .imgUpload .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
  .imgUpload .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  .imgUpload .el-upload-list__item > div {
    width: 100%;
    height: 100%;
  }
</style>
